﻿using Digitalmes.Scada.Configuration;
using Digitalmes.Scada.Handlers;

namespace Digitalmes.Scada.Forwarders;

/// <summary>
/// 本地转发服务接口
/// </summary>
internal sealed class ScadaNativeForwader : INativeForwarder
{
    private readonly IServiceProvider _serviceProvider;
    private readonly ILogger _logger;

    public ScadaNativeForwader(IServiceProvider serviceProvider, ILogger<ScadaNativeForwader> logger)
    {
        _serviceProvider = serviceProvider;
        _logger = logger;
    }

    public async Task<ResponseMessage> SendAsync(RequestMessage message, CancellationToken cancellationToken = default)
    {
        ResponseMessage response = new()
        {
            Request = message,
        };

        if (message.Flag != TagFlag.Trigger)
        {
            return response;
        }

        Dictionary<string, Type> map = new()
        {
            { TagDefine.PLC_Entry_Sign, typeof(EntryHandler) }, // 产品进站
            { TagDefine.PLC_Archive_Sign, typeof(ArchiveHandler) }, // 产品出站
            { TagDefine.PLC_Scan_Sign, typeof(ScanBarcodeHandler) }, // 扫关键物料码信号
            { TagDefine.PLC_ScanBatch_Sign, typeof(ScanBatchHandler) }, // 扫批次料码信号
            { TagDefine.PLC_Req_Sign, typeof(ReqHandler) }, // 扫批次料码信号
            { TagDefine.PLC_TakePartIn_Sign, typeof(TakePartInHandler) }, // NG口扫码上件信号
        };

        HandleResult result;
        var self = message.Self();

        if (map.TryGetValue(self.TagName, out var typ))
        {
            using var scope = _serviceProvider.CreateScope();
            var handler = (AbstractHandler)scope.ServiceProvider.GetRequiredService(typ!);
            result = await handler.HandleAsync(message, cancellationToken);
        }
        else
        {
            _logger.LogWarning("请求的标记名称 [{TagName}] 必须属于 [{Tags}] 其中的一种", self.TagName, string.Join(",", map.Keys));
            result = new() { State = 0 };
        }

        response.State = result.State;
        response.CallbackItems = result.CallbackItems;
        return response;
    }
}
